﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.Boss;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;

namespace DeHeng_Mes.Dao
{
    public class DeviceDao
    {

        /// <summary>
        /// 插入设备故障信息
        /// </summary>
        /// <param name="deviceFault"></param>
        /// <returns></returns>
        public int InsertError(DeviceFault deviceFault)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(deviceFault).ExecuteReturnIdentity();
            }
        }

        /// <summary>
        /// 查询单号结束时间是否是空
        /// </summary>
        /// <param name="deviceFault"></param>
        /// <returns></returns>
        public List<DeviceFault> EndTimeIsSave(DeviceFault deviceFault)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<DeviceFault>()
                     .Where(x => x.Operation == deviceFault.Operation)
                     .Where(x => x.StopEndTime != null)
                     .ToList();
            }
        }

        /// <summary>
        /// 更新结束时间、停机时长
        /// </summary>
        /// <param name="deviceFault"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateEndTimeError(DeviceFault deviceFault)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Updateable<DeviceFault>()
                    .SetColumns(x => x.StopEndTime == deviceFault.StopEndTime)
                    .SetColumns(x => x.FaultTime == deviceFault.FaultTime)
                    .Where(x => x.DeviceId == deviceFault.DeviceId && x.FaultMessage == deviceFault.FaultMessage && x.PlcName == deviceFault.PlcName)
                    .ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 检查是否存在该条数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="deviceNum"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public bool SelectMessage(string orderId, string deviceNum, DateTime dateTime, string plcName)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<DeviceFault>()
                    .Any(x => x.DeviceId == deviceNum &&
                               x.StopStartTime == dateTime &&
                               x.PlcName == plcName &&
                               x.OrderId == orderId);
            }
        }

        /// <summary>
        /// 查询指定订单是否存在报警信息，返回记录数
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>符合条件的记录数</returns>
        public int SelectOrderIsSave(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询符合条件的记录数
                return db.Queryable<DeviceWarn>()
                         .Count(x => x.OrderId == orderId);
            }
        }

        /// <summary>
        /// 更新指定订单和报警项的报警计数
        /// </summary>
        /// <returns>更新是否成功</returns>
        public bool UpdateWarnCount(string orderId, string type, string count)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 执行更新操作
                int rowsAffected = db.Updateable<DeviceWarn>()
                    .SetColumns(x => x.Count == count)
                    .Where(x => x.OrderId == orderId && x.WarnType == type)
                    .ExecuteCommand();
                // 返回是否有记录被更新
                return rowsAffected > 0;
            }
        }

        /// <summary>
        /// 插入新的报警计数数据
        /// </summary>
        /// <returns>插入的记录数</returns>
        public int InsertWarnCount(string orderId, string type, string count)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 创建新的 Warning 对象
                var warningData = new DeviceWarn
                {
                    OrderId = orderId,
                    WarnType = type,
                    Count = count
                };

                // 插入数据并返回插入的记录数
                return db.Insertable(warningData).ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据订单号查询数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<DeviceFault> QueryAll(string operation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<DeviceFault>().Where(x => x.Operation == operation).ToList();
            }
        }

        /// <summary>
        /// 获取采集时间
        /// </summary>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public TimeSpan getTimeByTraceCode(string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 假设表名为 "TraceTable" 并且时间字段为 "CreateTime"
                var result = db.Queryable<CollectionTime>()
                               .Where(t => t.TraceID == traceCode)
                               .Select(t => t.CreateTime) // 假设你想获取 CreateTime 字段
                               .Single();
                if (result == null)
                {
                    return DateTime.MinValue.TimeOfDay;
                }

                return result.TimeOfDay; // 返回查询到的时间值
            }
        }

        /// <summary>
        /// 根据Id删除所有相关订单的设备故障信息
        /// </summary>
        /// <param name="orderId"></param>
        public void DeleteAllByOrderId(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Deleteable<DeviceFault>()
                    .Where(x => x.OrderId == orderId)
                    .ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入未推送成功的设备报警数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="faultMessage"></param>
        /// <param name="faultType"></param>
        /// <param name="startTime"></param>
        public void InsertToFactory(BossAndon bossAndon, int code)
        {
            string status = "";
            if (code == 200)
                status = SystemConstant.Ok;
            var deviceFaultToFactory = new DeviceFaultToFactory()
            {
                DeviceId = bossAndon.DeviceId,
                FaultMessage = bossAndon.FaultMessage,
                FaultType = bossAndon.FaultType,
                StartTime = bossAndon.StartTime,
                OrderId = bossAndon.OrderId,
                ProcessId = bossAndon.ProcessId,
                Status = status
            };
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(deviceFaultToFactory).ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据条件查询是否存在该数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="faultMessage"></param>
        /// <param name="faultType"></param>
        /// <param name="startTime"></param>
        /// <returns></returns>
        public bool QueryByAll(string orderId, string operation,string deviceId, string faultMessage, string faultType, string startTime)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<DeviceFaultToFactory>()
               .Where(x => x.FaultMessage == faultMessage
                        && x.OrderId == orderId
                        && x.ProcessId == operation
                        && x.DeviceId == deviceId
                        && x.FaultType == faultType
                        && x.StartTime == startTime
                        && x.Status == SystemConstant.Ok)
               .Any();
            }
        }

        /// <summary>
        /// 根据Id清空故障推送信息缓存
        /// </summary>
        /// <param name="orderId"></param>
        public void DeleteAndonById(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Deleteable<DeviceFaultToFactory>()
                    .Where(x => x.OrderId == orderId);
            }
        }
    }
}
